import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/cart'

Page({

  /**
   * 页面的初始数据
   */
  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['shopList', 'count', 'checkedAll', 'totalPrice', 'login'],
      actions: ['getUser', 'delete', 'select', 'changeCheckedAll', 'changeShopNum', 'loadData'],
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 读取Mbox中的数据可能是异步的
    this.getUser()
    this.loadData()
  },

  onShow: function() {
    this.getUser()
    this.loadData()
  },

  onUnload: function () {
    this.storeBindings.destroyStoreBindings()
  },
  // 点击没有商品时的按钮
  handleClickTo(e) {
    if(!this.data.login) wx.navigateTo({
      url: '/pages/login/login',
    }) 
    else wx.switchTab({
      url: '/pages/home/index',
    })
  },

  // 点击全选
  onChange(e) {
    this.changeCheckedAll(e.detail)
  },

  // 选中一个
  onChangeChecked(e) {
    this.select(Number(e.currentTarget.id))
  },

  // 修改数量
  handleChangeNumber(e) {
    if(typeof e.detail === 'string') return
    this.changeShopNum(Number(e.currentTarget.id), e.detail)
  },

  // 点击删除
  // 左滑报错未解决
  handleToDelete(e) {
    this.delete(Number(e.currentTarget.id))
  },

  // 去详情页
  handleToDetail(e) {
    if(e.target.id !== '') return
    wx.navigateTo({
      url: `/pages/detail/detail?spuId=${e.currentTarget.id}&plateForm=1`,
    })
  }
})